package com.jse.service;

import java.util.HashMap;
import java.util.Map;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.entity.Record;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.weixin.at.impl.DaoAccessTokenStore;
import org.nutz.weixin.impl.WxApi2Impl;
import org.nutz.weixin.spi.WxApi2;

/**
 * 如果是集群部署请使用RedisAccessTokenStore
 */
@IocBean(args = { "refer:dao" })
public class WxConfigService {

	@Inject
	Dao dao;

	public WxApi2 getWxApi2(String wxid) {
		Record appInfo = dao.fetch("Wx_config", Cnd.where("id", "=", wxid));
		DaoAccessTokenStore myDaoAccessTokenStore = new DaoAccessTokenStore(dao);
		Map<String, Object> params = new HashMap<>();
		params.put("id", appInfo.get("id"));
		myDaoAccessTokenStore.setTableAccessToken("access_token");
		myDaoAccessTokenStore.setTableAccessTokenExpires("access_token_expires");
		myDaoAccessTokenStore.setTableAccessTokenLastat("access_token_lastat");
		myDaoAccessTokenStore
				.setFetch("select access_token,access_token_expires,access_token_lastat from wx_config where id=@id");
		myDaoAccessTokenStore.setUpdate(
				"update wx_config set access_token=@access_token, access_token_expires=@access_token_expires, access_token_lastat=@access_token_lastat where id=@id");
		myDaoAccessTokenStore.setParams(params);
		WxApi2Impl wxApi2 = new WxApi2Impl();
		wxApi2.setAppid(appInfo.getString("appid"));
		wxApi2.setAppsecret(appInfo.getString("appsecret"));
		wxApi2.setEncodingAesKey(appInfo.getString("encodingAESKey"));
		wxApi2.setToken(appInfo.getString("token"));
		wxApi2.setAccessTokenStore(myDaoAccessTokenStore);
		return wxApi2;
	}

}
